<template>
  <div class="flex-box">
    <div class="input_t">
      <el-input v-model="classname" placeholder="请输入班级名称" style="width: 200px;margin-right: 10px" clearable></el-input>
      <el-input v-model="materialname" placeholder="请输入资料名称" style="width: 200px;margin-right: 10px" clearable></el-input>
    </div>
    <div class="button_t">
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
    </div>
  </div>
  <div style="display: flex;justify-content: center">
    <el-table
      :data="materialData"
      border
      style="width: 59.4%">
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">
          {{ (currentPage - 1) * pagesize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
          label="班级"
          prop="name"
          width="180"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="老师"
          prop="teacherName"
          width="180"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="资料数量"
          prop="materialNum"
          width="180"
          align="center"
          header-align="center"
      ></el-table-column>
      <el-table-column
          label="操作"
          width="180"
          align="center"
          header-align="center"
      >
        <template #default="props">
          <el-button @click="addMaterial(props.row.classId)" type="primary">添加资料</el-button>
        </template>
      </el-table-column>
      <el-table-column
          type="expand"
          label="资料"
          width="180"
          align="center"
          header-align="center"
      >
        <template #default="props">
          <el-table :data="props.row.materials" border style="width: 100%">
            <el-table-column label="序号" width="80" align="center">
              <template #default="scope">
                {{ (currentPage - 1) * pagesize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
                label="标题"
                prop="title"
                align="center"
                width="180"
                header-align="center"
            ></el-table-column>
            <el-table-column
                label="视频"
                prop="videoPath"
                width="180"
                align="center"
                header-align="center"
            >
              <template #default="props">
                <el-button type="text" @click="openVideoDialog(props.row)" v-if="props.row.videoPath!=null">查看</el-button>
                <el-button type="text" @click="updateFile(props.row.materialId) " v-if="props.row.videoPath!=null">修改视频</el-button>
                <el-button type="text" class="red-text-btn"  @click="uploadFile(props.row.materialId) " v-if="props.row.videoPath===null">上传文件</el-button>
              </template>
            </el-table-column>
            <el-table-column
                label="封面"
                prop="videoPng"
                width="180"
                align="center"
                header-align="center"
            >
              <template #default="props">
                <el-button type="text" @click="openImageDialog(props.row)" v-if="props.row.videoPng!=null">查看</el-button>
                <el-button type="text" @click="updatePng(props.row.materialId) " v-if="props.row.videoPng!=null">修改封面</el-button>
                <el-button type="text" class="red-text-btn"  @click="uploadPng(props.row.materialId) " v-if="props.row.videoPng===null">上传封面</el-button>
              </template>
            </el-table-column>
            <el-table-column
                label="上传时间"
                prop="createdAt"
                width="180"
                align="center"
                header-align="center"
                :formatter="formatDate"
            ></el-table-column>
          </el-table>
        </template>

      </el-table-column>
    </el-table>
  </div>
  <div class="el_center">
    <el-pagination
        v-model:current-page="pageno"
        v-model:page-size="pagesize"
        :page-sizes="[10, 20, 40, 50]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog
      v-model="dialogVisibleadd"
      :title="diaTitle"
      width="500"
      :before-close="handleClose"
  >
    <el-form>
      <el-form-item label="标题">
        <el-input v-model="materialInfo.title" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="dialogVisibleadd = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog
      v-model="dialogVisiblevideo"
      :title="diaTitle"
      width="500"
      :before-close="handleClose"
  >
    <el-upload
        class="upload-video"
        drag
        action
        :auto-upload="false"
        :on-change="handleVideoChange"
        :show-file-list="false"
        accept="video/*"
    >
      <template v-if="!videoFile">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将视频文件拖到此处，或<em>点击选择</em></div>
      </template>
      <template v-else>
        <div class="file-preview">
          <i class="el-icon-video-camera"></i>
          <div class="file-info">
            <div>{{ videoFile.name }}</div>
            <div>{{ formatFileSize(videoFile.size) }}</div>
          </div>
        </div>
      </template>
    </el-upload>
    <el-button
        type="success"
        :loading="uploading"
        :disabled="!isFormValid"
        @click="submitUpload"
    >
      {{ uploading ? '上传中...' : '开始上传' }}
    </el-button>
  </el-dialog>
  <el-dialog
      v-model="dialogVisiblecover"
      :title="diaTitle"
      width="500"
      :before-close="handleClose"
  >
    <el-upload
        class="upload-cover"
        :auto-upload="false"
        :on-change="handleCoverChange"
        :show-file-list="false"
        accept="image/*"
    >
      <template v-if="!coverFile">
        <el-button type="primary">选择封面图片</el-button>
      </template>
      <template v-else>
        <div class="cover-preview">
          <img :src="coverPreviewUrl" alt="封面预览" class="cover-image" />
          <div class="cover-actions">
            <el-button type="danger" @click.stop="removeCover">移除</el-button>
          </div>
        </div>
      </template>
    </el-upload>
    <el-button
        type="success"
        :loading="uploading"
        :disabled="!isFormValid"
        @click="submitUpload"
    >
      {{ uploading ? '上传中...' : '开始上传' }}
    </el-button>
  </el-dialog>
  <!-- 视频弹窗 -->
  <el-dialog v-model="videoDialogVisible" title="视频预览" width="80%" destroy-on-close>
    <video controls width="100%" :src="videoUrl" />
  </el-dialog>
  <el-dialog v-model="imageDialogVisible" title="图片预览" width="80%">
    <img :src="imageUrl" style="width:100%; height:auto;" />
  </el-dialog>
</template>
<script setup>
import {ref,onMounted,computed,reactive} from 'vue'
import {Search,AddMaterial} from '../../../api/material.js'
import request from "../../../utils/request.js";
import {ElMessage} from "element-plus";
import dayjs from "dayjs";

const currentPage = ref(1)
const classname = ref('')
const uploading = ref(false)
const coverPreviewUrl = ref('')
const materialname = ref('')
const videoFile = ref(null)
const coverFile = ref(null)
const materialData = ref([
  {
    classId: '',
    name: "",
    teacherId: '',
    teacherName: "",
    materialNum: '',
    materials: [
      {
        materialId: '',
        classId: '',
        title: "",
        videoPath: "",
        videoPng: "",
        isDeleted: '',
        createdAt: ""
      }
    ]
  }
])
const classList = ref([
  {
    classId:'',
    name:'',
    teacherName:''
  }
])
const pageno = ref(1)
const pagesize = ref(10)
const total = ref(0)
const size = ref(false)
const disabled = ref(false)
const background = ref(false)
const dialogVisibleadd = ref(false)
const dialogVisiblevideo = ref(false)
const dialogVisiblecover = ref(false)
const diaTitle = ref('')
const materialInfo=ref({
  classId:'',
  title:''
})
const materialId = ref('')
const uploadFile = (id) => {
  materialId.value = id
  diaTitle.value = '上传视频'
  dialogVisiblevideo.value = true
}
const updateFile = (id) => {
  materialId.value = id
  diaTitle.value = '修改视频'
  dialogVisiblevideo.value = true
}
const uploadPng = (id) => {
  materialId.value = id
  diaTitle.value = '上传图片'
  dialogVisiblecover.value = true
}
const updatePng = (id) => {
  materialId.value = id
  diaTitle.value = '修改图片'
  dialogVisiblecover.value = true
}
const handleSizeChange = (val) => {
  pagesize.value = val
  search()
}
const handleCurrentChange = (val) => {
  pageno.value = val
  search()
}
const handleClose = (done) => {
  dialogVisibleadd.value = false
  dialogVisiblecover.value = false
  dialogVisiblevideo.value = false
  done()
}
const search = () => {
  Search({
    classname:classname.value,
    materialname:materialname.value,
    pageno:pageno.value,
    pagesize:pagesize.value
  }).then(res=>{
    materialData.value = res.data.data.records
    total.value = res.data.data.total
  })
}
const confirm = async () => {
  AddMaterial(materialInfo.value).then(res=>{
    ElMessage.success('添加成功')
    dialogVisibleadd.value = false
    search()
  })
  materialInfo.value={}
}
const addMaterial = (classId) => {
  console.log(classId)
  dialogVisibleadd.value = true
  materialInfo.value.classId = classId
}
const handleVideoChange = (file) => {
  if (file.raw.type.startsWith('video/')) {
    videoFile.value = file.raw
  } else {
    ElMessage.error('请选择有效的视频文件')
  }
}

// 处理封面图片选择
const handleCoverChange = (file) => {
  if (file.raw.type.startsWith('image/')) {
    coverFile.value = file.raw
    // 生成预览图
    const reader = new FileReader()
    reader.onload = (e) => {
      coverPreviewUrl.value = e.target.result
    }
    reader.readAsDataURL(file.raw)
  } else {
    ElMessage.error('请选择有效的图片文件')
  }
}

// 移除封面
const removeCover = () => {
  coverFile.value = null
  coverPreviewUrl.value = ''
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 表单验证
const isFormValid = computed(() => {
  return (
      videoFile.value || coverFile.value
  )
})

// 提交上传
const submitUpload = async () => {
  if (!isFormValid.value) return
  console.log('materialId=',materialId.value)
  const formData = new FormData()

  if (dialogVisiblecover.value === true) {
    formData.append('coverImage', coverFile.value || '');
    formData.append('videoFile', '');
    dialogVisiblecover.value = false;
  } else {
    formData.append('videoFile', videoFile.value || '');
    formData.append('coverImage', '');
    dialogVisiblevideo.value = false;
  }
  formData.append('materialId', materialId.value)
  console.log(formData.get('videoFile'))

  uploading.value = true

  try {
    const response = await request.post('/material/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success({
      message: `上传成功！`,
      duration: 5000
    })

    // 重置表单
    videoFile.value = null
    coverFile.value = null
    coverPreviewUrl.value = ''
    form.value = { title: '', description: '' }
  } catch (error) {
    const msg = error.response?.data?.message || error.message
  } finally {
    uploading.value = false
  }
  search()
}
const videoDialogVisible = ref(false);
const videoUrl = ref('');

// 打开视频弹窗
const openVideoDialog = (row) => {
  // 构造视频的完整 URL
  const fileName = row.videoPath;
  videoUrl.value = `http://localhost:8080/api/material/video/${encodeURIComponent(fileName)}`;
  videoDialogVisible.value = true;
};
const imageDialogVisible = ref(false);

// 图片 URL
const imageUrl = ref('');

// 打开图片弹窗
const openImageDialog = (row) => {
  // 构造图片的完整 URL
  const fileName = row.videoPng;
  imageUrl.value = `http://localhost:8080/api/material/cover/${encodeURIComponent(fileName)}`;
  imageDialogVisible.value = true;
};
const formatDate=(row, column, cellValue)=> {
  // 使用 dayjs 格式化日期
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '';
}
onMounted(()=>{
  search()
})
</script>
<style lang="less" scoped>
.flex-box {
  display: flex;
  justify-content: space-between;
  padding-left: 21%;
  padding-right: 21%;
}
.el_center{
  display: flex;
  justify-content: center;
}
.el_table{
  margin-top: 20px;
  width: 980px;
}
/* 普通样式 */
.red-text-btn {
  color: #ff0000;
}

/* 悬停状态 */
.red-text-btn:hover {
  color: #cc0000 !important;
}

</style>
